import { Component, ViewChild, ViewChildren, ViewContainerRef } from '@angular/core';
import {ICellEditorAngularComp} from '@ag-grid-community/angular';
import { ApiService } from '@core/services/http/api.service';
import { NgSelectComponent} from '@shared/apes/ng-select';

@Component({
  selector: 'apes-cell-uom-select',
  template: `
         <ng-select #select [items]="items" [clearable]="false" (keydown)="onKeyDown($event)"
              style="height:100%"
              [ngStyle]="{'width': params.column.actualWidth+'px' }"
              bindLabel="name"
              [(ngModel)]="inputValue" >
         </ng-select>
    `,
  styles: []
})
export class EditorUomSelectComponent implements ICellEditorAngularComp {
  options = [];
  items:any;
  inputValue: any;
  params: any
  apesConfig: any;

  @ViewChild(NgSelectComponent,{static:false})
  private select: NgSelectComponent;

  constructor(private api:ApiService) {

}

  agInit(params: any): void {
    this.params = params;
    this.inputValue = params.value;
    this.apesConfig = this.extend(params);
    if(params.value){
      this.api.post('cm.product.uom.findAllByCategory', {'id': params.value.id}).subscribe((body) => {
        this.items = body;
      });
    }

  }

  extend(data: any){
    let result = {};
    for (let key in data) {
      let value = data[key];
      if(key === 'context'){
        result['ctx'] = value;
      } else{
        result[key] = value;
      }
    }
    return result;
  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.select.focus();
    });
  }
  isPopup(): boolean {
    this.select.open();
    return true;
  }


  getValue(): any {
    let result;
    if (this.inputValue === undefined || this.inputValue === null) {
      result = null;
      this.params.value = null;
    } else {
      result = this.inputValue;
      this.params.value = this.inputValue;
    }
    return result;
  }

  // refresh(params: any): boolean {
  //     return undefined;
  // }

  onKeyDown(event): void {
    let key = event.which || event.keyCode;
    if (key === 38 || key === 40) {
      this.preventDefaultAndPropagation(event);

      if (key == 38) {
        // up
        console.log('up');
        //this.selectedIndex = this.selectedIndex === 0 ? this.vegetables.length - 1 : this.selectedIndex - 1;
      } else if (key == 40) {
        // down
        // this.selectedIndex = this.selectedIndex === this.vegetables.length - 1 ? 0 : this.selectedIndex + 1;
        console.log('down');
      }
      //this.selectFavouriteVegetableBasedOnSelectedIndex();
    }
  }

  private preventDefaultAndPropagation(event) {
    event.preventDefault();
    event.stopPropagation();
  }
}
